<template>
	<view class="topic">
		<view class="question">{{topic.question}}</view>
		<view class="info">
			<text class="difficulty">难度: {{topic.difficulty}}</text>
			<text class="views">学习次数: {{topic.views}}</text>
		</view>
		<view class="answer">
			<image :src="topic.cover" mode="aspectFit"/>
			<rich-text :selectable="true" :nodes="htmlAnswer"></rich-text>
		</view>
	</view>
</template>

<script>
	import { fetchData,markdown, STUDY_HISTORY } from "../../utils";
	export default {
		data() {
			return {
				topic:{}
			};
		},
		async onLoad({id}){
			const topic = await fetchData({
				url:`/topic/${id}`
			});
			this.topic = topic;
			uni.setNavigationBarTitle({
				title:topic.question
			})
			this.addTopicToStudyHistory(topic);
		},
		methods:{
			addTopicToStudyHistory(topic){
				//先获取老的学习历史，是一个题目的数组
				const studyHistory = uni.getStorageSync(STUDY_HISTORY)||[];
				//给题目添加一个学习时间的字段,是一个当前的时间有时间戳
				topic.studyTime = Date.now();
				//在学习历史中找有没有和当前要添加的题目ID相同的条目
				const existingTopicIndex = studyHistory.findIndex(item=>item.id === topic.id);
				//先把老数据删除
				if(existingTopicIndex !== -1){
					studyHistory.splice(existingTopicIndex,1);
				}
				//再向数组的头部添加最新的题目
				studyHistory.unshift(topic);
				uni.setStorageSync(STUDY_HISTORY,studyHistory)
			}
		},
		computed:{
			htmlAnswer(){
				return markdown.render(this.topic.answer||'');
			}
		}
	}
</script>

<style lang="scss" scoped>
.topic{
	padding:20rpx;
	background-color: #FAFAFA;
	.question{
		font-size:36rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
		color:#333333;
		text-align: center;
		background-color: #FFF;
		padding:20rpx;
		border-radius: 15rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	.info{
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
		background-color: #FFF;
		padding: 20rpx;
		border-radius: 15rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		.difficulty,.views{
			font-size:28rpx;
			color:#777;
		}
	}
	.answer{
		margin-top:20rpx;
		image{
			width:100%;
			height:400rpx;
			object-fit: cover;
			border-radius: 15rpx;
			margin-bottom: 20rpx;
		}
		/deep/ .language-html{
			white-space: pre-wrap;
			word-wrap: break-word;
		}
	}
}
</style>
